import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Objects;
import java.util.Scanner;

public class TcpClient {
    public static void main(String[] args) throws UnknownHostException, IOException {
        //创建客户端对象，连接服务器
        //指定服务器ip   端口 8888
        //注意这里的IP和端口都是服务器规定好的
        Socket client = new Socket("127.0.0.1", 8888);
        System.out.println("客户端:" + client);
        //获取IO流
        InputStream is = client.getInputStream();
        OutputStream os = client.getOutputStream();
        while (true) {
            //给服务器端发送数据
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入发送给服务器的信息");
            String msg = scan.nextLine();
            if (Objects.equals(msg, "quit")) {
                System.out.println("退出程序");
                break;
            } else {
                //字符串转byte数组
                byte[] b = msg.getBytes();
                //将数据写到输出流
                os.write(b);
                //客户端接收 解析服务端的消息
                byte[] cb = new byte[1024];
                int length = is.read(cb);
                if (length != -1) {
                    System.out.println(new String(cb, 0, length));
                }
            }

        }
        //关闭资源  注意处理异常，判空
        os.close();
        is.close();
        client.close();
    }
}